package server_commands;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Vector;

import server.ServerSocketConnection;
import connection_modul.DatabaseConnection;

public class ADD_MSGSCommand extends Command {

	
	public ADD_MSGSCommand(String parameter) {
		setCode(ADD_MSGS_CMD);
		setParameter(parameter);
	}
	
	
	@Override
	public boolean executeCommand(ServerSocketConnection connection, DatabaseConnection dbConnection) {

		String username = getParameter();
		
		String addMsgsQuery = "SELECT tblUsers.username, tblUsers.nickname, tblUsers.email, tblUsers.ip_address, tblUsers.local_address, tblUsers.port, tblUsers.status, tblUsers.reg_date, tblUsers.avatar " +
		  					  "FROM tblUsers, tblOffActivities " +
		  					  "WHERE tblOffActivities.username = '" + username + "' AND tblUsers.username = tblOffActivities.add_message";

		
		try {
			dbConnection.doStatement(addMsgsQuery);

			ArrayList<Vector> addMsgsList = new ArrayList<Vector>(dbConnection.data);
			
			dbConnection.clearDataStore();
			
			connection.setMessage( "140 AddMsgs " + addMsgsList.size() );
			
			for (int i = 0; i < addMsgsList.size(); i++) {
				StringBuffer entry = new StringBuffer();
				
				for (int j = 0; j < addMsgsList.get(i).size(); j++) {
					entry.append(addMsgsList.get(i).get(j));
					if (j < addMsgsList.get(i).size() - 1) {
						entry.append(" ");
					}
				}
				
				connection.setMessage(entry.toString());
			}
			
			String updateSQLQuery = "DELETE FROM tblOffActivities " +
				"WHERE tblOffActivities.username = '" + username + "' AND tblOffActivities.add_message IS NOT NULL";
			

			dbConnection.doUpdateStatement(updateSQLQuery);
			
		} catch (SQLException e) {			
			e.printStackTrace();
			dbConnection.doRollBack();
			
			return false;
		}
		
		dbConnection.doCommit();
		
		return true;
	}
}
